<?php

declare(strict_types=1);

namespace App\Http\Middleware;

use App\Services\Code\HttpResponse;
use Closure;
use Illuminate\Support\Facades\Log;
use Lcobucci\JWT\Parser;

class MiniToken
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        Log::info('request params', $request->input());

        // 测试环境跳过
        if (!prod()) {
            return $next($request);
        }

        $token = request()->header('token');

        try {
            $token = (new Parser())->parse($token);
        } catch (\Throwable $e) {
            Log::error('token parse err');

            return response()->json(HttpResponse::respFail(HttpResponse::CODE_TOKEN_ERR, 'token parse err'));
        }

        $jti    = $token->getHeader('jti');
        $secret = $token->getClaim('secret');
        $exp    = $token->getClaim('exp');

        if ($jti !== env('MINI_APPID')) {
            return response()->json(HttpResponse::respFail(HttpResponse::CODE_TOKEN_ERR, 'token appid err'));
        }

        if ($secret !== env('MINI_SECRET')) {
            return response()->json(HttpResponse::respFail(HttpResponse::CODE_TOKEN_ERR, 'token err'));
        }

        if ($exp < time()) {
            return response()->json(HttpResponse::respFail(HttpResponse::CODE_TOKEN_EXP, 'token exp'));
        }

        return $next($request);
    }
}
